package cn.steel.controller.supplier;

import cn.steel.domain.entity.Message;
import cn.steel.domain.entity.User;
import cn.steel.service.MessageService;
import cn.steel.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Controller
@RequestMapping("/supplier/message")
@RequiredArgsConstructor
public class SupplierMessageController {

    private final UserService userService;
    private final MessageService messageService;

    @GetMapping
    public String messagePage(Model model) {
        // 获取当前登录用户
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String currentUsername = userDetails.getUsername();
        User supplier = userService.getUserByUsername(currentUsername);

        if (!"SUPPLIER".equals(supplier.getRole())) {
            throw new IllegalStateException("只有供应商可以访问此页面");
        }

        // 获取购买过商品的买家列表
        List<User> allBuyers = userService.findUsersByRole("BUYER");
        Set<Long> buyerIdsWithOrders = userService.findBuyersWithOrders(supplier.getId());
        List<User> buyers = allBuyers.stream()
                .filter(buyer -> buyerIdsWithOrders.contains(buyer.getId()))
                .collect(Collectors.toList());

        for (User buyer : buyers) {
            long unreadCount = messageService.getUnreadMessageCount(supplier.getId());
            buyer.setUnreadCount(unreadCount);
        }

        model.addAttribute("buyers", buyers);
        log.info("Loaded supplier message page, buyers count={}", buyers.size());
        return "supplier/message";
    }

    @GetMapping("/chat/{buyerId}")
    public String chatWithBuyer(@PathVariable Long buyerId, Model model) {
        // 获取当前登录用户
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String currentUsername = userDetails.getUsername();
        User supplier = userService.getUserByUsername(currentUsername);

        if (!"SUPPLIER".equals(supplier.getRole())) {
            throw new IllegalStateException("只有供应商可以访问此页面");
        }

        // 获取购买商信息
        User buyer = userService.getUserById(buyerId);
        if (!"BUYER".equals(buyer.getRole())) {
            throw new IllegalStateException("只能与购买商聊天");
        }

        // 验证是否有交易关系
        Set<Long> buyerIdsWithOrders = userService.findBuyersWithOrders(supplier.getId());
        if (!buyerIdsWithOrders.contains(buyerId)) {
            throw new IllegalStateException("该买家没有购买过您的商品");
        }

        // 获取聊天记录并标记为已读
        List<Message> messages = messageService.getMessagesBetweenUsers(supplier.getId(), buyerId);
        messageService.markMessagesAsRead(supplier.getId(), buyerId);

        // 获取购买过商品的买家列表用于左侧显示
        List<User> allBuyers = userService.findUsersByRole("BUYER");
        List<User> buyers = allBuyers.stream()
                .filter(b -> buyerIdsWithOrders.contains(b.getId()))
                .collect(Collectors.toList());

        for (User b : buyers) {
            long unreadCount = messageService.getUnreadMessageCount(supplier.getId());
            b.setUnreadCount(unreadCount);
        }

        model.addAttribute("contacts", buyers);
        model.addAttribute("contact", buyer);
        model.addAttribute("selectedContactId", buyerId);
        model.addAttribute("messages", messages);
        model.addAttribute("currentUserId", supplier.getId());
        model.addAttribute("role", "SUPPLIER");
        log.info("Loaded chat page for supplierId={} and buyerId={}", supplier.getId(), buyerId);
        return "supplier/chat";
    }

    @PostMapping("/send")
    public String sendMessage(@RequestParam Long receiverId, @RequestParam Long senderId, @RequestParam String content, Model model) {
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String currentUsername = userDetails.getUsername();
        User supplier = userService.getUserByUsername(currentUsername);

        if (!"SUPPLIER".equals(supplier.getRole())) {
            throw new IllegalStateException("只有供应商可以发送消息");
        }

        User receiver = userService.getUserById(receiverId);
        if (!"BUYER".equals(receiver.getRole())) {
            throw new IllegalStateException("只能向购买商发送消息");
        }

        messageService.sendMessage(senderId, receiverId, content);

        return "redirect:/supplier/message/chat/" + receiverId;
    }
}